﻿@{
	Layout = "_Layout.cshtml";
}
@RenderBody()
@section header
{
	@if (IsSectionDefined("header"))
	{
		@RenderSection("header")
	}
	else
	{
		bool isTearOff = bool.Parse(Request.QueryString["isTearOff"]);
		bool noTabs = bool.Parse(Request.QueryString["noTabs"]);
		bool isNew = bool.Parse(Request.QueryString["isNew"]);
		string paramVarName = Request.QueryString["paramVarName"];
		string itemTypeLabel = Request.QueryString["itemTypeLabel"];
		string itemTypeName = Request.QueryString["itemTypeName"];
		string itemID = Request.QueryString["itemID"];
		bool isEditMode = bool.Parse(Request.QueryString["isEditMode"]);
		string databaseName = Request.QueryString["databaseName"];
		string viewType = Request.QueryString["viewType"];

		<link rel="Configuration" href="../cbin/AllAssemblies.config.xml" />
		<style type="text/css">
			@@import "../styles/default.css";

			#statusbar, #tearoff_menu, #relationships
			{
				display: none;
			}

			#branding .status-column, #page_status .status-column, #status .status-column
			{
				padding: 0 10px !important;
			}

			#page_status .status-column
			{
				text-align: center;
			}

			#tearoffmenucontrol
			{
				width: 100%;
				border: 0px;
				padding: 0px;
				margin: 0px;
			}

			#center
			{
				top: 55px !important;
			}
		</style>
		<script defer type="text/javascript" id="dnd" startmanual="true" src="../javascript/dragDropHelper.js"></script>
		<script type="text/javascript">
					@{if (noTabs)
						{
							<text>var hideTabs = true;</text>
						}
						else
						{
							<text>
			require(["Aras/Client/Frames/Relationships"]);
			require(["Aras/Client/UI/Components/MarkupViewer"]);

			var hideTabs = false;
			</text>
						}
					}
			aras.browserHelper.hidePanels(window, ["locationbar"]);
			var LocationSearches = new Object();

			var item = @(paramVarName).item;
			var itemID = @(paramVarName).itemID;
			var itemTypeName = @(paramVarName).itemTypeName;
			var itemType = @(paramVarName).itemType;
			var viewMode = @(paramVarName).viewMode;
			var isEditMode = @(paramVarName).isEditMode;
			var isTearOff = @(paramVarName).isTearOff;
			@(paramVarName) = undefined;

			var relationshipsGridInfoProvider =
			{
				getInstance: function(relshipsGridId){ return this; },
				getMenu: function(){return window.tearOffMenuController;},
				waitForMenu: true
			};

			function getItem()
			{
				return item;
			}

			function setItem(value)
			{
				item = value;
			}

			function updateRootItem(itemNd)
			{
				if (!itemNd)
				{
					top.aras.AlertError("Failed to get the " + window.itemTypeName, "", "");
					return false;
				}

				if (itemNd.getAttribute("type") != window.itemTypeName)
				{
					top.aras.AlertError("Invalid ItemType specified: (" + itemNd.getAttribute("type") + ").");
					return false;
				}

				itemID = itemNd.getAttribute("id");
				var wasLocked = (top.aras.isLockedByUser(item) || top.aras.isTempEx(item));
				item   = itemNd;

				if (isEditMode)
				{
					isEditMode = wasLocked;
					setEditMode();
				}
				else
				{
					isEditMode = wasLocked;
					setViewMode();
				}
			}

			function setEditMode()
			{
				var prevMode = isEditMode;
				isEditMode = true;
				var formNd = top.aras.uiGetForm4ItemEx(item, "edit");
				var bodyNd = formNd.selectSingleNode("Relationships/Item[@@type='Body']");
				fieldNds = bodyNd.selectNodes("Relationships/Item[@@type='Field' and (not(@@action) or (@@action!='delete' and @@action!='purge'))]");
				var fieldsHash = new Array();
				var fieldsToDraw = top.aras.uiGetFieldsToDraw(fieldNds, item, "edit");

				for (var i = 0; i < fieldNds.length; i++)
				{
					var fieldNd = fieldNds[i];
					var fieldId = fieldNd.getAttribute("id");
					var fieldType = top.aras.getItemProperty(fieldNd, "field_type");

					var frame = document.getElementById("instance");
					if (!frame) continue;
					var setExpHandler = eval("frame.contentWindow.expression_" + fieldId + "_setExpression");
					if(setExpHandler)
						setExpHandler(isEditMode);
				}

				document.title = top.aras.getResource("", "ui_methods_ex.itemtype_label_item_keyed_name", "@itemTypeLabel", top.aras.getKeyedNameEx(item));

				@{if (isTearOff)
					{
					<text>
				if (document.getElementById("tearoff_menu") && document.getElementById("tearoff_menu").contentWindow.setEditMode)
					document.getElementById("tearoff_menu").contentWindow.setEditMode();
				</text>
					}
				}

				var addFormID = top.aras.uiGetFormID4ItemEx(item,"add");
				var editFormID = top.aras.uiGetFormID4ItemEx(item,"edit");
				var viewFormID = top.aras.uiGetFormID4ItemEx(item,"view");

				var prevFormID = (document.getElementById("instance")) ? document.getElementById("instance").contentWindow.document.formID : "";
				if (item.getAttribute("action") == "add")
				{
					if(prevFormID != addFormID)
					{
						if (document.getElementById("instance"))
							top.aras.uiShowItemInFrameEx(document.getElementById("instance").contentWindow, item, "add", 0);
					}
					else
					{
						if (document.getElementById("instance") && document.getElementById("instance").contentWindow.document.forms.MainDataForm)
						{
							top.aras.uiPopulateFormWithItemEx(document.getElementById("instance").contentWindow.document.forms.MainDataForm, item, itemType, true);
						}
					}
				}
				else if ((prevMode != isEditMode && editFormID != viewFormID) || editFormID != prevFormID)
				{
					if (document.getElementById("instance"))
						top.aras.uiShowItemInFrameEx(document.getElementById("instance").contentWindow, item, "edit", 0);
				}
				else if (document.getElementById("instance") && document.getElementById("instance").contentWindow.document.getElementById("MainDataForm"))
					top.aras.uiPopulateFormWithItemEx(document.getElementById("instance").contentWindow.document.forms.MainDataForm, item, itemType, true);

				if (window.relationships && window.relationships.contentWindow.setEditMode)
					window.relationships.contentWindow.setEditMode();
			}

			function setViewMode()
			{
				var prevMode = isEditMode;
				isEditMode = false;
				var formNd = top.aras.uiGetForm4ItemEx(item, "edit");
				var bodyNd = formNd.selectSingleNode("Relationships/Item[@@type='Body']");
				fieldNds = bodyNd.selectNodes("Relationships/Item[@@type='Field' and (not(@@action) or (@@action!='delete' and @@action!='purge'))]");
				var fieldsHash = new Array();
				var fieldsToDraw = top.aras.uiGetFieldsToDraw(fieldNds, item, "edit");

				for (var i = 0; i < fieldNds.length; i++)
				{
					var fieldNd = fieldNds[i];
					var fieldId = fieldNd.getAttribute("id");
					var fieldType = top.aras.getItemProperty(fieldNd, "field_type");

					var frame = document.getElementById("instance");
					if (!frame) continue;
					var setExpHandler = eval("frame.contentWindow.expression_" + fieldId + "_setExpression");
					if(setExpHandler)
						setExpHandler(isEditMode);
				}

				document.title = top.aras.getResource("", "ui_methods_ex.itemtype_label_item_keyed_name_readonly", "@itemTypeLabel", top.aras.getKeyedNameEx(item));

				@{if (isTearOff)
					{
						<text>
				if (document.getElementById("tearoff_menu") && document.getElementById("tearoff_menu").contentWindow.setViewMode)
					document.getElementById("tearoff_menu").contentWindow.setViewMode();
				</text>
					}
				}

				var editFormID = top.aras.uiGetFormID4ItemEx(item,"edit");
				var viewFormID = top.aras.uiGetFormID4ItemEx(item,"view");
				var prevFormID = (document.getElementById("instance")) ? document.getElementById("instance").contentWindow.document.formID : "";

				if ((prevMode != isEditMode && editFormID != viewFormID) || viewFormID != prevFormID)
				{
					if (document.getElementById("instance")) top.aras.uiShowItemInFrameEx(document.getElementById("instance").contentWindow, item, "view", 0);
				}
				else if (document.getElementById("instance") && document.getElementById("instance").contentWindow.document.forms.MainDataForm)
				{
					top.aras.uiPopulateFormWithItemEx(document.getElementById("instance").contentWindow.document.forms.MainDataForm, item, itemType, false);
				}

				if (window.relationships && window.relationships.setViewMode)
				{
					window.relationships.setViewMode();
				}
			}

			function turnWindowReadyOn()
			{
				//that script will set windowReady = true and cause menuUpdate
				window.windowReady = true;
				window.updateMenuState();
				DragDropHelper.disableDnD( window );
			}

			var statusbar, simpleTabbar, relationships;
			var relationshipsControl;
			var borderContainerWidget, bottomContainerWidget, bottomSplitter;
			onload = function onload_handler()
			{
				@{if(isTearOff)
					{
						<text>
				try
				{
					if(window.aras)
					{
						window.aras = new Aras(window.aras.findMainArasObject());
					}
				}
				catch (e)
				{

				}
				</text>
					}
				}

				borderContainerWidget = dijit.byId("BorderContainer");
				centerBorderContainer = dijit.byId("CenterBorderContainer");
				bottomContainerWidget = dijit.byId("bottom");

				if (!hideTabs)
				{
					bottomSplitter = centerBorderContainer.getSplitter("bottom");
					dojo.connect(bottomSplitter, "_stopDrag", window, "onBottomSplitterMoved");
				}

				//window.gridHeightRatio = window.hideTabs ? 0.3 : calculateGridHeightRatio();

				turnWindowReadyOn();
				onresize_handler();
				IfNeedResize();
			}

			function onBottomSplitterMoved(evt)
			{
				window.gridHeightRatio = calculateGridHeightRatio();
			}

			function calculateGridHeightRatio()
			{
				var containerHeight = borderContainerWidget.domNode.offsetHeight,
					statusBarHeight = bottomContainerWidget.domNode.offsetHeight,
					topBorderPosition = bottomSplitter.domNode.offsetTop + bottomSplitter.domNode.offsetHeight,
					corelationValue = 4; // summary of border widths, paddings and margins, which affect height

				return (containerHeight - topBorderPosition - statusBarHeight - corelationValue) / containerHeight;
			}

			function onresize_handler()
			{
				if (!borderContainerWidget)
				{
					return;
				}
				var containerHeight = borderContainerWidget.domNode.offsetHeight;
				borderContainerWidget.previousHeight = borderContainerWidget.previousHeight || 0;

				if (!window.hideTabs && containerHeight != borderContainerWidget.previousHeight)
				{
					relationshipsControl.domNode.style.height = parseInt(containerHeight * window.gridHeightRatio) + "px";
					borderContainerWidget.previousHeight = containerHeight;
					borderContainerWidget.layout();
				}
			}
			window.onresize = onresize_handler;

			var repeatTimer ;//This timer eliminates several consecutive "resizes"

			//refresh the content size after maximization is not fully loaded window
			function refreshSizeContentPanes()
			{
				if (repeatTimer)
				{
					window.clearTimeout(repeatTimer);
					delete repeatTimer;
				}
				repeatTimer = window.setTimeout(function()
				{
					var maxSize = screen.availWidth;
					document.getElementById("top").style.width = maxSize;
					document.getElementById("center").style.width = maxSize;
					if (document.getElementById("centerMiddle"))
					{
						document.getElementById("centerMiddle").style.width = maxSize;
					}
					var borderContainer = dijit.byId("BorderContainer");
					document.getElementById("bottom").style.width = maxSize;
					if (borderContainer)
					{
						borderContainer.resize();
					}
					if (borderContainer)
					{
						borderContainer.layout();
					}
				}, 100);
			}

			// step2 : check size of the content after DOMContentLoaded
			window.addEventListener("DOMContentLoaded", function ()
			{
				IfNeedResize();
				checkIframeReady();
			});
			// step3 : check size of the content after iframe.onload
			function onload_iframe_handler()
			{
				IfNeedResize();
			}

			var timeWaiting = 100;// 100 * 100ms delay = 10000ms or 10sec max time for waiting iframe ready

			// step 4: check size of the contnet after iframe.document.complete (appears somewhat later than iframe.onload event)
			function checkIframeReady()
			{
				var instanceFrame = window.frames["instance"];
				if (instanceFrame &&
				instanceFrame.document &&
				instanceFrame.document.readyState != "complete")
				{
					window.setTimeout(function()
					{
						timeWaiting = timeWaiting -1;
						if (timeWaiting > 0)
						{
							checkIframeReady();
						}
						else
						{
							return;
						}
					}, 100);
					return;
				}
				else
				{
					IfNeedResize();
				}
			};

			function IfNeedResize()
			{
				var windowHeight = document.body.offsetHeight;
				windowWidth = document.body.offsetWidth,
				topNd = document.getElementById("top"),
				centerNd = document.getElementById("center"),
				middleCenterNd = document.getElementById("centerMiddle"),
				bottomNd = document.getElementById("bottom");
				var sizeTop,
				sizeCenter,
				sizeMiddleCenter,
				sizeBottom;

				if (middleCenterNd)
				{
					sizeMiddleCenter = getWH(middleCenterNd);
				}

				if (topNd && centerNd && bottomNd)
				{
					sizeTop = getWH(topNd);
					sizeCenter = getWH(centerNd);
					sizeBottom = getWH(bottomNd);

					if (!sizeMiddleCenter)
					{
						sizeMiddleCenter =
						{
							height: 0, wodith: 0
						};
					}

					var marginFix = sizeMiddleCenter.height ? 8 : 2;//2px or 8px margin
					summaryHeight = sizeTop.height + sizeCenter.height + sizeMiddleCenter.height + sizeBottom.height +  marginFix;
					summaryWidth = sizeTop.width;
					if(summaryHeight!=windowHeight || summaryWidth != windowWidth)
					{
						refreshSizeContentPanes();
					}
				}

				function getWH(node)
				{
					if(node)
					{
						return {
							height: node.offsetHeight,
							width: node.offsetWidth
						};
					}
				}
			}

			window.addEventListener("DOMContentLoaded", function ()
			{
				var frm = document.getElementById("instance").contentWindow;
				@{if(isNew)
					{
						<text>top.aras.uiShowItemInFrameEx(frm, item, "add", 0);</text>
					}
					else
					{
						<text>top.aras.uiShowItemInFrameEx(frm, item, "@((isEditMode)?"edit":"view")", 0);</text>
					}
				}
			});
		</script>
		<script type="text/javascript" id="item_window_script" src="../javascript/item_window.js"></script>
		<script type="text/javascript" src="../javascript/item_window_common.js"></script>
	}
}

@section center
{
	@if (IsSectionDefined("center"))
	{
		@RenderSection("center")
	}
	else
	{
		bool noTabs = bool.Parse(Request.QueryString["noTabs"]);
		bool isNew = bool.Parse(Request.QueryString["isNew"]);
		string itemTypeName = Request.QueryString["itemTypeName"];
		string itemID = Request.QueryString["itemID"];
		bool isEditMode = bool.Parse(Request.QueryString["isEditMode"]);
		string databaseName = Request.QueryString["databaseName"];

		<div data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="region: 'center', gutters:false, liveSplitters:false" style="width: 100%; height: 100%;" id="CenterBorderContainer">
			@if (!noTabs)
			{
				<div data-dojo-type="Aras/Client/Controls/Relationships" data-dojo-props="region: 'bottom', splitter: true, queryString: {db:'@databaseName', ITName: '@itemTypeName', itemID: '@itemID', editMode:'@(isEditMode?1:0)', tabbar:'1', toolbar:'1', where:'tabview'}, window : window" id="centerMiddle" style="height: 230px;left: -20px;">
					<script type="dojo/connect" data-dojo-event="startup">
						window.relationshipsControl = this;
						//compatibility code
						clientControlsFactory.createControl("Aras.Client.Frames.Relationships", {relationshipsControl: this}, function(control) {
						window.relationships = control;
						});
					</script>
				</div>
			}

			<!--If this "div" is higher than div with id="centerMiddle" then relTab  will be jumping in ie9 when resizing window -->
			<div data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center', splitter: true" id="center2">
				@if (itemTypeName == "CAD" || itemTypeName == "Document")
				{
					<div data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'sidebar', gutters:true, liveSplitters:false" id="middleBorderContainer2">
						<div data-dojo-type="dijit/layout/ContentPane" data-dojo-props="splitter:true, region:'center'" baseclass="dijitContentPaneNoPadding" id="formContentPane">
							<iframe id="instance" src="blank.html" frameborder="0" width="100%" height="100%" onload="onload_iframe_handler()"></iframe>
						</div>
						<div data-dojo-type="Aras/Client/UI/Components/MarkupViewer" data-dojo-props="splitter:true, region:'right'" style="width: 0;"></div>
					</div>
				}
				else
				{
					<iframe id="instance" src="blank.html" frameborder="0" width="100%" height="100%" onload="onload_iframe_handler()"></iframe>
				}
			</div>
		</div>
	}
}